//admin_show_product.js reborn!
//{{{
var dialog_form_el = $( "#dialog-form" );
var dialog_message_el = $( '#dialog-message' );
//判断传入的对象是否为空
function is_null_obj( obj ){
	for ( var item in obj ){ 
		return false;
	}
       	return true;
}
//初始化 jqueryui 按钮
//@param object this_button_el 需要初始化的按钮
function init_button( this_button_el ){
	if( typeof( this_button_el ) != 'object' || is_null_obj( this_button_el ) ){
                throw new TypeError( '传入的 this_button_el 类型不匹配,应该为一个对象,且不能为空' );
	}
	//@todo 如果使用 switch 则依赖 HTML 中 class 出现的顺序
	//对于添加按钮
	if( this_button_el.hasClass( 'add' ) ){
		this_button_el.button({
			icons: {
				primary: "ui-icon-plus"
			},
			text: false
		});
		this_button_el.click( function(){
			show_product_info_edit_form( this_button_el , 'add' );
		});
		return;
	}
	//对于 detail 按钮
	if( this_button_el.hasClass( 'detail' ) ){
	        this_button_el.button({
			icons: {
				primary: "ui-icon-triangle-1-s"
			},
			text: false
		});
		this_button_el.click( function(){       
			show_product_at_spec_class_info( this_button_el );
		});
		return;
	 }
	 //对于 del 按钮
	 if( this_button_el.hasClass( 'del' ) ){
		this_button_el.button({
			icons: {
				primary: "ui-icon-close"
			},
			text: false
		});
		this_button_el.click( function(){
			//删除当前 tr 
			delete_tr( this_button_el );
		});
		return;
	 }
	 //对于 edit 按钮
	 if( this_button_el.hasClass( 'edit' ) ){
		this_button_el.button({
			icons: {
				primary: "ui-icon-gear"
			},
			text: false
		});
		this_button_el.click( function(){
		        show_product_info_edit_form( this_button_el , 'edit' );
		});
		return;
	}
}
//循环找到主 tr (主要针对商品服务信息)，以便刷新其中的按钮
//@param object this_tr_el 当前按钮所处的 tr
function find_main_tr( this_tr_el ){
         if( !this_tr_el.is( 'tr' ) ){
                 throw new Error( '提供给 find_main_tr() 的参数需要是 tr 对象' );
         }
	 //循环找到主 tr 
	 return this_tr_el.find( '.product_id' ).html() == '' ? this_tr_el : (function(){
		 var this_main_product_tr_el = this_tr_el.prev();
		 while( 1 ){
			 if( this_main_product_tr_el.find( '.product_id' ).html() != '' ){
				 break;
			 }else{
				 this_main_product_tr_el = this_tr_el.prev();
			 }
		 }
                 return this_main_product_tr_el;
	 })();
}
//显示商品编辑表单
//@param object this_button_el 当前点击的按钮对象 
//@param string submit_to_url 指定提交的 url
//@param string type 指定按钮的操作类型 需要显示表单的有两种操作 第一种为添加一个新的关联 add ,第二为修改当前的信息 edit
function show_product_info_edit_form( this_button_el , type ){
        if( typeof( this_button_el ) != 'object' || is_null_obj( this_button_el ) ){
                throw new TypeError( '传入的 this_tr_el 为空,应该为一个对象' );
	}
	//从 this_tr_el 中获取默认信息
	var product_default_info = get_product_info_in_this_tr( this_button_el );
	//使用默认值填充表单
	var title_el = $( "#title" ),
		describe_el = $( "#describe" ),
		price_el = $( "#price" ),
		product_class_id_el = $( '#product_class_id' );
        title_el.val( product_default_info.title );
        describe_el.val( product_default_info.describe );
        price_el.val( product_default_info.price );
        //使能表单
        dialog_form_el.dialog( "destroy" );
        var select_el = dialog_form_el.find( '#product_class_id' );
        var product_class_id = '';
	switch( type ){
	case 'edit':
                 switch( product_default_info.tr_type ){
                         case 'product':
                                 submit_to_url = '/admin/ajax_do_edit_product/';
                                 break;
                         case 'product_in_spec_class':
                                 submit_to_url = '/admin/ajax_do_edit_product_at_spec_class/';
                                 break;
                         default:
                                 throw new Error( '使用了无效的tr_type' );
                 }
		 //对于已经有的关联以及仅仅是修改商品的默认信息 则只显示相关信息而不显示列表
	 	 //判断的依据是该 tr 不能直接通过查找 .product_id 元素的
		 //值来获取 product_id 
		 if( product_default_info.product_id == '' ){
			 //在子 list 中
			 //替换原来的 select 标签为 h3 
			 select_el.next( '<h3>' + product_default_info.product_class_name_cn + '</h3>' );
			 select_el.hide();
			 product_info
		 }else{
			 //在商品列表中
			 select_el.parent().hide();
		 }
                 product_class_id = product_default_info.class_id;
		 break;
	 case 'add':
                 submit_to_url = '/admin/ajax_do_add_new_product_at_spec_class/';
		 //更新 select 中的 option 
		 if( !get_available_product_class_list( product_default_info.product_id ) ){
			 //返回列表为空	disable 这个 button 
			 //@todo 算不算一个异常?
			 this_button_el.button( 'disable' );
			 return;
		 }
		 break;
	 default:
		 throw new Error( '没有指定,或者使用了无效的操作类型' );
	 }                    
	 dialog_form_el.dialog({
                 modal: true ,
		 width: 480 ,
		 height: 650 ,
		 buttons: {
		 "提交": function(){
                        if( type == 'add' ){
                                //对于添加操作 在提交表单的时候才能获取该值 
                                product_class_id = product_class_id_el.val();
                        }
                        $.post( submit_to_url , 
                        {
                                 "product_id": product_default_info.product_id ,
                                 "title": title_el.val() ,
                                 "describe": describe_el.val() ,
                                 "price": price_el.val() ,
                                 "product_class_id": product_class_id
                        } ,
			function( res ){
                                check_ajax_res_priv_err( res );1
				if( res.res == "TRUE" ){
					 var this_tr_el = this_button_el.parent().parent();
                                         //写入成功
                                         //关闭弹出窗口
                                         dialog_form_el.dialog( "destroy" );
                                         //对于 add  操作判断是否已经有 detail 按钮存在
					 if( type == 'add' && this_tr_el.find( '.detail' ).length <= 0 ){
                                                 //添加一个新的 add 按钮
                                                 this_button_el.before( "<span class='button detail'>添加</sapn>" );
                                         }
                                         //如果为更新 product_in_spec_class 中的信息
                                         //刷新列表
                                         switch( product_default_info.tr_type ){
                                                 case 'product_in_spec_class':
                                                        //刷新当前主 tr 中的 button 
                                                        var main_tr_el = find_main_tr( this_tr_el );
					                enable_button( main_tr_el );
                                                        //更新该 tr
                                                        this_tr_el.find( '.price' ).text( price_el.val() );
                                                        this_tr_el.find( '.describe' ).text( describe_el.val() );
                                                        this_tr_el.find( '.title' ).text( title_el.val() );
                                                        break;
                                                 case 'product':
                                                        if( type == 'edit' ){
                                                                //如果 type 是 edit
                                                                //更新 tr 中的信息
                                                                this_tr_el.find( '.price' ).text( price_el.val() );
                                                                this_tr_el.find( '.describe' ).text( describe_el.val() );
                                                                this_tr_el.find( '.title' ).text( title_el.val() );
                                                        }
                                                        if( type == 'add' ){
                                                                //如果 type 是 add 
                                                                //刷新显示新添加的服务商品关联信息
                                                                show_product_at_spec_class_info( this_button_el );
                                                        }
                                                        enable_button( this_tr_el );
                                                        break;
                                                 default:
                                                        throw new Error( "更新完成后使用了无效的tr_type" );
                                         }
                                 }else{
                                        dialog_form_el.dialog( "destroy" );
				        throw new Error( '写入信息失败' );
				 }
				 } , "json" ); }, 
		 "取消": function(){
		         $( this ).dialog( "close" );	 
		 } 
		 }//end of button   
         });//end of dialog
}
//删除一行
//@param object this_button_el 触发该事件的 button 元素
function delete_tr( this_button_el ){
	//获得当前 tr 的引用
	var this_tr_el = this_button_el.parent().parent();
	//当前 tr 中的信息
	var product_info_in_this_tr = get_product_info_in_this_tr( this_button_el );
	dialog_message_el.dialog({
		title: "是否确认删除该条目", 
		text: '',
		resizable: false,
		height:140,
		modal: true,
		buttons:{
			"确认":function(){
				switch( product_info_in_this_tr.tr_type ){
				//仅仅删除一个商品服务关联
                                case 'product_in_spec_class':
					$.post( '/admin/ajax_do_del_product_at_spec_class/' ,
						"product_id=" + product_info_in_this_tr.product_id + 
						"&&product_class_id=" + product_info_in_this_tr.class_id ,
						function( res ){
                                                        check_ajax_res_priv_err( res );
                                                        if( res.check_priv == 'FALSE' ){
                                                                $( this ).dialog( "close" );
                                                        }
							if( res.res == "TRUE" ){
								//如果已经没有可以显示的商品服务连接
								//则 删除该商品主 tr 中的 detail 按钮
								if( res.remain == '0' ){
									//循环找到主 tr 
									var this_main_product_tr_el = find_main_tr( this_tr_el );
									this_main_product_tr_el.find( '.detail' ).remove();
								}
                                                                //刷新主 tr 中所有的按钮
								enable_button( this_main_product_tr_el );
                                                                dialog_message_el.dialog( "close" );
							}else{
                                                                dialog_message_el.dialog( "close" );
                                                                throw new Error( "删除商品服务关联信息是错误" );
                                                        }	 
							this_tr_el.fadeOut();
						} , "json" 
					);
					break;
                                //删除整个商品 包括商品服务关联
				case 'product':
					 $.post( '/admin/product/del/' , "product_id=" + product_info_in_this_tr.product_id ,
					 function( res ){
                                                check_ajax_res_priv_err( res );
						if( res.res == "TRUE" ){
							this_tr_el.fadeOut();
                                                        //相应的商品服务关联也得消失
                                                        while( 1 ){
                                                                //@todo 防止超时
                                                                //setTimeout( 'break' , 3000 ); ...
                                                                var this_tr_next_el = this_tr_el.next();
                                                                if( this_tr_next_el.hasClass( 'product_at_spec_class_info_tr' ) ){
                                                                        this_tr_next_el.fadeOut();
                                                                        this_tr_el = this_tr_next_el;
                                                                }else{
                                                                        break;
                                                                }
                                                        }                        
						 }else{
                                                        dialog_message_el.dialog( "close" );
							throw new Error( '删除product信息时,ajax错误.' );
						 }
						 dialog_message_el.dialog( "close" );
					 }, "json" );  
					 break;
				default:
					throw new Error( '删除 <tr> 时没有指定具体的 tr_type ' );
				}
				},
			"取消":function(){
				 dialog_message_el.dialog( "close" );
			}
		}
	});
}
//删除(隐藏?)某商品的所有关联服务信息
function remove_product_at_spec_class_info( this_button_el , this_tr_el ){
	 this_button_el.unbind( 'click' );
	 this_button_el.bind( 'click' , function(){
                 show_product_at_spec_class_info( this_button_el ) 
         });
	 var this_tr_next_el = this_tr_el.next();
	 while( 1 ){ 
		 if( this_tr_next_el.attr( 'class' ) == 'product_at_spec_class_info_tr' ){
			 this_tr_next_el.remove();
			 this_tr_next_el = this_tr_el.next();
		 }else{
			 return;
		 }
	 }
}
//显示某商品的所有关联服务信息
function show_product_at_spec_class_info( this_button_el ){
	 var this_tr_el = this_button_el.parent().parent();
         //先删除之前的信息
         remove_product_at_spec_class_info( this_button_el , this_tr_el ); 
	 var product_info_in_this_tr = get_product_info_in_this_tr( this_button_el );
	 if( product_info_in_this_tr.tr_type != 'product' ){
		 throw new Error( '不能对不是显示 product 信息的行调用用这个方法' );
	 }
	 $.get( '/admin/ajax_get_product_at_spec_class_info/' , { "product_id": product_info_in_this_tr.product_id }, 
		 function( res ){
                         if( res.res == "FALSE" ){
                                 throw new Error( "获取列表失败请稍后再试" );
                         }
			 $.each( res , function( index , product_info ){
				 //显示相应的商品信息
				 var product_at_spec_class_info_tr = "<tr id='this_product_is-" + 
					 product_info.product_class_id + '-' + product_info.product_id+ "'class='product_at_spec_class_info_tr'>";
					 product_at_spec_class_info_tr += "<td style='background:#ccc;' class='align_center class_name_cn product_class_info_td'>" +
						 product_info.product_class_name_cn + "</td>" +
						 "<td style='background:#ccc;' class='product_class_info_td title'>" + product_info.title + "</td>" +
						 "<td style='background:#ccc;'  class='product_class_info_td describe'>" + product_info.describe + "</td>" +
						 "<td style='background:#ccc;' class='align_center product_class_info_td price' >" + product_info.price + "</td>" +  
						 "<td style='background:#ccc;' class='align_center product_class_info_td'><a class='edit button' href='javascript:void(0);' rel='" +
						 product_info.product_class_id + "' >编辑<a/><a class='del button' href='javascript:void(0);' rel='" + 
						 product_info.product_class_id + "'>删除<a/></td></tr>";
	 			 this_tr_el.after( product_at_spec_class_info_tr );
				 var new_tr = this_tr_el.next();
				 new_tr.show();
				 //再次点击 detail 按钮删除这些 tr
                                 var detail_button_in_this_tr_el = this_tr_el.find( '.detail' );
				 detail_button_in_this_tr_el.unbind( 'click' );
				 detail_button_in_this_tr_el.bind( 'click' , function(){
					 remove_product_at_spec_class_info( detail_button_in_this_tr_el , this_tr_el );
				 });
				 //使能新添加 tr 中的按钮
				 enable_button( new_tr );
			 });//end of each 
		 } , "json"
	 );  
}	
//遍历使能所有指定范围的按钮
//@param object domain 指定的范围
function enable_button( domain ){
	//遍历所有含有 .button 的元素
	if( !is_null_obj( domain ) ){
		 var button_els = $( domain ).find( '.button' ); 
	}else{
		 var button_els = $( '.button' );
	}
	button_els.each( function( index , el ){
		var this_button_el = $( el );
                this_button_el.unbind( 'click' );
		init_button( this_button_el );
	});
}
//获得可选的服务(因为一个商品只能和一个服务关联一次)
//如果存在设置 select 中的 option 并返回 true ，否则
//返回 false 
//@param number product_id 指定商品 id  
function get_available_product_class_list( product_id ){
	var has_available_product_class = true;
	$.ajax({ 
		url: "/admin/ajax_get_avilable_product_class_list/" , 
		data: "product_id=" + product_id , 
		success: function( res ){
			var this_select_options = '';
			var select_el = dialog_form_el.find( '#product_class_id' );
			//先清空原有的选项
			select_el.empty();
			$.each( res , function( index , product_class_info ){
				this_select_options += "<option value='" + product_class_info.class_id + "'>" + 
				product_class_info.product_class_name_cn + "</option>";
			});
			select_el.append( this_select_options );
			select_el.parent().show();
			if( this_select_options == '' ){
				has_available_product_class = false;
			}
		} ,
		type: 'get' ,
		dataType: "json" ,
		async: false ,
		//设置超时时间为 5s 
		timeout: 5
	});
	return has_available_product_class;
}
//通过 this_button_el 获取当前行的信息
//@param object this_button_el 触发本事件的 按钮元素的引用
function get_product_info_in_this_tr( this_button_el ){
        var this_tr_el = this_button_el.parent().parent();
        var this_product_id = this_tr_el.find( '.product_id' ).text();
        var product_info = {};
        product_info.product_id = this_tr_el.find( '.product_id' ).text();
        product_info.title = this_tr_el.find( '.title' ).text();
        product_info.describe = this_tr_el.find( '.describe' ).text();
        product_info.price = this_tr_el.find( '.price' ).text();
        product_info.product_class_name_cn = this_tr_el.find( '.class_name_cn' ).text();
        product_info.tr_type = product_info.product_class_name_cn != '' ? 'product_in_spec_class' : 'product';
        if( product_info.tr_type == 'product_in_spec_class' ){
                var this_tr_el = this_button_el.parent().parent();
                //通过该 tr 的 id 获取 product_id 信息
                product_info.class_id = this_tr_el.attr( 'id' ).split( '-' )[1];
                product_info.product_id = this_tr_el.attr( 'id' ).split( '-' )[2];
        }
        return product_info;
}

try{
	enable_button();
}catch( e ){
	console.error( e.message );
}
